# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::BackgroundMigration::BackfillArchivedAndTraversalIdsToVulnerabilityStatistics, feature_category: :vulnerability_management do
  let(:organizations) { table(:organizations) }
  let(:namespaces) { table(:namespaces) }
  let(:projects) { table(:projects) }
  let(:vulnerability_statistics) { table(:vulnerability_statistics, database: :sec) }
  let(:args) do
    min, max = vulnerability_statistics.pick('MIN(id)', 'MAX(id)')
    {
      start_id: min,
      end_id: max,
      batch_table: 'vulnerability_statistics',
      batch_column: 'id',
      sub_batch_size: 100,
      pause_ms: 0,
      connection: ::SecApplicationRecord.connection
    }
  end

  let(:organization) { organizations.create!(name: 'Organization', path: 'organization') }
  let!(:group_namespace) do
    namespaces.create!(
      name: 'gitlab-org',
      path: 'gitlab-org',
      type: 'Group',
      organization_id: organization.id
    ).tap { |namespace| namespace.update!(traversal_ids: [namespace.id]) }
  end

  let!(:other_group_namespace) do
    namespaces.create!(
      name: 'gitlab-com',
      path: 'gitlab-com',
      type: 'Group',
      organization_id: organization.id
    ).tap { |namespace| namespace.update!(traversal_ids: [namespace.id]) }
  end

  let!(:project) { create_project('gitlab', group_namespace) }
  let!(:other_project) { create_project('www-gitlab-com', other_group_namespace) }

  subject(:perform_migration) { described_class.new(**args).perform }

  before do
    [project, other_project].each do |p|
      create_vulnerability_statistic(project: p)
    end
  end

  it 'backfills traversal_ids and archived', :aggregate_failures do
    perform_migration

    vulnerability_statistics.find_each do |vulnerability_statistic|
      project = projects.find(vulnerability_statistic.project_id)
      namespace = namespaces.find(project.namespace_id)

      expect(vulnerability_statistic.traversal_ids).to eq(namespace.traversal_ids)
      expect(vulnerability_statistic.archived).to eq(project.archived)
    end
  end

  def create_vulnerability_statistic(project:)
    namespace = namespaces.find(project.namespace_id)
    vulnerability_statistics.create!(
      project_id: project.id,
      total: 0,
      critical: 0,
      high: 0,
      medium: 0,
      low: 0,
      unknown: 0,
      info: 0,
      letter_grade: 0,
      created_at: Time.current,
      traversal_ids: namespace.traversal_ids,
      updated_at: Time.current
    )
  end

  def create_project(name, group)
    project_namespace = namespaces.create!(
      name: name,
      path: name,
      type: 'Project',
      organization_id: organization.id
    )

    projects.create!(
      namespace_id: group.id,
      project_namespace_id: project_namespace.id,
      organization_id: organization.id,
      name: name,
      path: name,
      archived: true
    )
  end
end
